//
//  AuthenticateAddTableViewController.m
//  LPTClient
//
//  Created by apple on 2018/12/10.
//  Copyright © 2018 zhaodd. All rights reserved.
//

#import "AuthenticateAddTableViewController.h"
#import "AuthHeaderTableViewCell.h"
#import "AuthCommonTableViewCell.h"
#import "AuthInputViewTableViewCell.h"
#import "AuthUploadTableViewCell.h"
#import "ErrorShowTableViewCell.h"
#import "LPTBaseRequest.h"
#import "MMProgressHUD.h"
#import "AFNetworking.h"

@interface AuthenticateAddTableViewController ()<UINavigationControllerDelegate, UITextFieldDelegate, UITextViewDelegate, UIImagePickerControllerDelegate>
{
    UIButton *commitBtn;
}
@property (nonatomic, strong) NSArray *array1;//
@property (nonatomic, strong) NSArray *array2;//

@property (nonatomic, strong) UITextField *cur_textField;
@property (nonatomic, strong) UITextView *cur_textView;

@property (nonatomic, assign) NSInteger step; //  1 填写资料  2 上传资格证  3 等待审核

@property (nonatomic, strong) NSString *intro; // 医生介绍
@property (nonatomic, copy) NSString *m_key;

@end

@implementation AuthenticateAddTableViewController


+ (instancetype)instance
{
    UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Authen" bundle:nil];
    AuthenticateAddTableViewController *vc = [storyBoard instantiateInitialViewController];
    return vc;
}



//- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
//{
//    if (self.step == 0) {
//        return YES;
//    }
//
//    if (self.step == 1) {
//        UIAlertController *alerVC = [UIAlertController alertControllerWithTitle:@"确定返回吗？" message:@"您正在编辑资料，返回会丢失已填写内容，确定返回吗？" preferredStyle:UIAlertControllerStyleAlert];
//        [alerVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        }]];
//        [alerVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            self.step = 0;
//            [self.navigationController popViewControllerAnimated:YES];
//        }]];
//        [self presentViewController:alerVC animated:YES completion:NULL];
//    } else if (self.step > 1){
//        self.step --;
//        [self reloadStep];
//    }
//
//    return NO;
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.navigationController.navigationBar.delegate = self;
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.step = 1;
    
    //   type  1 输入框      2 选择
    self.array1 = @[@{ @"key":@"name",@"name": @"姓名" , @"v": @"", @"type": @"1", @"errMsg":@"请输入姓名"},
                       @{ @"key":@"sex",@"name": @"性别" , @"v": @"男", @"type": @"2"},
                       @{ @"key":@"identity",@"name": @"身份证号" , @"v": @"", @"type": @"1",  @"errMsg":@"请输入身份证号"},
                       @{ @"key":@"hospital",@"name": @"所在医院" , @"v": @"", @"type": @"1", @"errMsg":@"请输入所在医院"},
                       @{ @"key":@"professional_title",@"name": @"专业职称" , @"v": @"住院医师", @"type": @"2"},
                       @{ @"key":@"major",@"name": @"擅长专业" , @"v": @"", @"type": @"1",  @"errMsg":@"请输入擅长专业"},];
    
    self.array2 = @[@{ @"key":@"figure_file_id", @"imageInfo":@"", @"name": @"上传医生照片(必填)" , @"desc": @"在有效期内 字迹清晰 没有遮挡、涂鸦", @"errMsg":@"请上传医生照片"},
                    @{ @"key":@"identity_front_file_id",@"imageInfo":@"",  @"name": @"上传身份证正面(必填)" , @"desc": @"在有效期内 字迹清晰 没有遮挡、涂鸦", @"errMsg":@"请上传身份证正面照片"},
                    @{ @"key":@"identity_back_file_id",@"imageInfo":@"",  @"name": @"上传身份证反面(必填)" , @"desc": @"在有效期内 字迹清晰 没有遮挡、涂鸦", @"errMsg":@"请上传身份证反面照片"},
                    @{ @"key":@"certificates1",@"imageInfo":@"",  @"name": @"上传医师证书一(必填)" , @"desc": @"在有效期内 字迹清晰 没有遮挡、涂鸦", @"errMsg":@"请至少上传一张医师证书照片"},
                    @{ @"key":@"certificates2",@"imageInfo":@"",  @"name": @"上传医师证书二(可选)" , @"desc": @"在有效期内 字迹清晰 没有遮挡、涂鸦", @"errMsg":@"请至少上传一张医师证书照片"},
                    @{ @"key":@"certificates3",@"imageInfo":@"",  @"name": @"上传医师证书三(可选)" , @"desc": @"在有效期内 字迹清晰 没有遮挡、涂鸦", @"errMsg":@"请至少上传一张医师证书照片"}];
    
    commitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    commitBtn.frame = CGRectMake(15, 35, kScreenWidth - 30, 45);
    commitBtn.backgroundColor = [UIColor whiteColor];
    [commitBtn.layer setMasksToBounds:YES];
    [commitBtn.layer setCornerRadius:22.5];
    [commitBtn setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"#F7941E"]] forState:UIControlStateNormal];
    [commitBtn addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    [commitBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [self.view addSubview:commitBtn];
    
    UIView *v = [[UIView alloc] init];
    v.frame = CGRectMake(0, 0, kScreenWidth, 90);
    [v addSubview:commitBtn];
    
    self.tableView.tableFooterView = v;
}

- (void)reloadStep
{
    if (self.step == 3) {
        [commitBtn setTitle:@"返回" forState:UIControlStateNormal];
    }
    [self.tableView reloadData];
}
#pragma mark 下一步点击事件
- (void)nextAction:(UIButton *)btn
{
    if (self.step == 1) {
        if (self.cur_textField) {
            [self.cur_textField resignFirstResponder];
        }
        if (self.cur_textView) {
            [self.cur_textView resignFirstResponder];
        }
        if (![self isStepOneOK]) {
            return;
        }
        
        self.step = 2;
        [self reloadStep];

    }else if (self.step == 2) {

        // 判断空数据 ， 和后3张照片的3选一
        if (![self isStepTwoOK]) {
            return;
        }
        
        [self requestCommit];
    }else if (self.step == 3) {
        // 刷新用户资料
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refresh_login_userinfo" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.step == 1) {
        return 3;
    } else if (self.step == 2 || self.step == 3) {
        return 2;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (self.step == 1) {
        if (section == 1) {
            return self.array1.count;
        }
    } else if (self.step == 2) {
        if (section == 1) {
            return self.array2.count;
        }
    }
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSInteger section = indexPath.section;
    
    if (section == 0) {
        AuthHeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AuthHeaderTableViewCellID" forIndexPath:indexPath];
        [cell selected:self.step-1];

        return cell;
    } else {
        
        if (self.step == 1) {
            
            if (section == 1) {
                AuthCommonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AuthCommonTableViewCellID" forIndexPath:indexPath];
                
                NSDictionary *dict = self.array1[indexPath.row];
                [cell refreshWithDict:dict];
                
                return cell;
            } else if (section == 2) {
                AuthInputViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AuthInputViewTableViewCellID" forIndexPath:indexPath];
                
                NSDictionary *dict = @{@"title":@"医生简介", @"placeholder":@"请对自己简单介绍下"};
                [cell refreshWithDict:dict];
                
                return cell;
            }
            
        } else if (self.step == 2) {
            
            if (section == 1) {
                AuthUploadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AuthUploadTableViewCellID" forIndexPath:indexPath];
                
                NSDictionary *dict = self.array2[indexPath.row];
                [cell refreshWithDict:dict];
                
                return cell;
            }
        } else if (self.step == 3) {
            
            if (section == 1) {
                
                ErrorShowTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ErrorShowTableViewCellID" forIndexPath:indexPath];
                
                [cell showWithType:ErrorShowTypeInReview];
                
                return cell;
            }
        }
        
    }
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
 
    if (self.step == 1) {
        NSDictionary *dict = self.array1[indexPath.row];
        NSString *name = dict[@"name"];
        
        if ([name isEqualToString:@"性别"]) {
            [self actionSheetMake:1];
        } else if ([name isEqualToString:@"专业职称"]) {
            [self actionSheetMake:2];
        }
        
    } else if (self.step == 2) {

    }
}

// type 1 性别    2 职称
- (void)actionSheetMake:(NSInteger)type
{
    NSString *title = @"选择性别";
    NSArray *array = @[@"男",@"女"];
    if (type == 2) {
        title = @"选择专业职称";
        array = self.majors;
    }
    UIAlertController *alerVC = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    for (int i=0; i<[array count]; i++) {
        [alerVC addAction:[UIAlertAction actionWithTitle:array[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            if (type == 1) {
                [self customSetValueForKey:@"sex" value:action.title ];
            }else if (type == 2) {
                [self customSetValueForKey:@"professional_title" value:action.title];
            }
        }]];
    }
    
    [alerVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];

    [self presentViewController:alerVC animated:YES completion:NULL];
}

// 根据 key 获取不能多少的字符长度
- (NSString *)minLengthFromKey:(NSString *)key value:(NSString *)value
{
    if ([key isEqualToString:@"name"] && value.length<2) {
        return @"姓名不能少于两个字符";
    }else if ([key isEqualToString:@"identity"] && value.length!=18) {
        return @"身份证号格式有误";
    }else if ([key isEqualToString:@"hospital"]) {
        if (value.length < 5) {
            return @"所在医院不能少于5个字符";
        } else if (value.length > 30) {
            return @"所在医院不能超过30个字符";
        }
    }else if ([key isEqualToString:@"introduce"]) {
        if (value.length < 30) {
            return @"医生简介不能少于30个字符";
        } else if (value.length > 300) {
            return @"医生简介不能超过300个字符";
        }
    }else if ([key isEqualToString:@"major"]) {
        if (value.length < 20) {
            return @"擅长专业不能少于20个字符";
        } else if (value.length > 150) {
            return @"擅长专业不能超过150个字符";
        }
    }
    return @"";
}

- (BOOL)isStepOneOK
{
    NSString *errMsg = nil;
    
    
    for (int i=0; i<[self.array1 count]; i++) {
        NSDictionary *dict = self.array1[i];
        NSString *key = dict[@"key"];
        NSString *value = dict[@"v"];
        if (value.length == 0) {
            errMsg = dict[@"errMsg"];
            break;
        }else {
            errMsg = [self minLengthFromKey:key value:value];
            if (errMsg && errMsg.length!=0) {
                break;
            }
        }
    }
    
    if (!errMsg || errMsg.length == 0) {
        
        // 判断 intro
        if (self.intro.length == 0) {
            errMsg = @"请输入医生简介";
        }else if (self.intro.length < 30){
            errMsg = @"医生简介不能少于30个字符";
        }else if (self.intro.length > 300) {
            errMsg = @"医生简介不能多于300个字符";
        }
    }
    
    if (errMsg && errMsg.length!=0) {
        [MMProgressHUD show];
        [MMProgressHUD dismissWithError:errMsg];
        return NO;
    }
    return YES;
}
// 第二步是否OK
- (BOOL)isStepTwoOK
{
    NSString *errMsg = nil;
    NSInteger errIndex = 0;
    for (int i=0; i<[self.array2 count]; i++) {
        NSDictionary *dict = self.array2[i];
        NSString *key = dict[@"key"];
        ImageInfo *imgInfo = dict[@"imageInfo"];
        
        if ([key hasPrefix:@"certificates"]) {
            // 后3张在这里判断
            if ([imgInfo isMemberOfClass:[ImageInfo class]]) {
                errIndex ++;
                continue;
            }
        }else {
            if (![imgInfo isMemberOfClass:[ImageInfo class]]) {
                errMsg = dict[@"errMsg"];;
                break;
            }
        }
    }
    
    if (errMsg && errMsg.length!=0) {
        [MMProgressHUD show];
        [MMProgressHUD dismissWithError:errMsg];
        return NO;
    }
    if (errIndex == 0) {
        [MMProgressHUD show];
        [MMProgressHUD dismissWithError:@"请至少上传一张医师证书"];
        return NO;
    }
    return YES;
}
// 后3个在这里哦


#pragma mark 提交所有数据
- (void)requestCommit
{
    [MMProgressHUD showWithStatus:@"提交中"];
    
    NSMutableDictionary *postDict = [NSMutableDictionary dictionaryWithCapacity:1];
    
    NSString *errMsg = nil;
    for (int i=0; i<[self.array1 count]; i++) {
        NSDictionary *dict = self.array1[i];
        NSString *key = dict[@"key"];
        NSString *value = dict[@"v"];
        if ([key isEqualToString:@"sex"]) {
            value = [NSString stringWithFormat:@"%@", [NSNumber numberWithInteger:[self sexIndex:value]]];
        }else if ([key isEqualToString:@"professional_title"]) {
            value = [NSString stringWithFormat:@"%@", [NSNumber numberWithInteger:[self.majors indexOfObject:value]]];
        }
        [postDict setValue:value forKey:key];
    }

    // intro
    [postDict setValue:self.intro forKey:@"introduce"];
    
    // 所有图片
    NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:1];
    for (int i=0; i<self.array2.count; i++) {
        NSDictionary *dict = self.array2[i];
        NSString *key = dict[@"key"];
        ImageInfo *imgInfo = dict[@"imageInfo"];
        if ([key hasPrefix:@"certificates"]) {
            if (imgInfo) {
                if ([imgInfo isMemberOfClass:[ImageInfo class]]) {
                    [certificates addObject:[NSNumber numberWithInteger:imgInfo.id]];
                }
            }
        }else {
            [postDict setValue:[NSNumber numberWithInteger:imgInfo.id] forKey:key];
        }
    }
    if (certificates.count > 0) {
        [postDict setValue:certificates forKey:@"certificates"];
    }
    
    if (errMsg) {
        [MMProgressHUD dismissWithError:errMsg];
        return;
    }
    NSLog(@"认证上传数据：%@", postDict);

    
    LPTBaseRequest *request = [[LPTBaseRequest alloc] initWithApi:@"/api/save_credential" withBody:[postDict copy] withMethod:YTKRequestMethodPOST];
    
    [request startRequestCompleteSuccess:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        
        [MMProgressHUD dismiss];
        self.step = 3;
        [self reloadStep];
        
    } completeFailed:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        [MMProgressHUD dismissWithError:request.msg];
    }];

}


#pragma mark UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.cur_textField = textField;
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSString *key = objc_getAssociatedObject(textField, @"custom_key");
    [self customSetValueForKey:key value:textField.text];
}

// 根据key 给数据设置值
- (void)customSetValueForKey:(NSString *)mkey value:(NSString *)value
{
    NSMutableArray *mutableArr = [NSMutableArray arrayWithArray:self.array1];
    
    for (int i=0; i<[self.array1 count]; i++) {
        NSDictionary *dict = self.array1[i];
        NSString *key = dict[@"key"];
        if ([key isEqualToString:mkey]) {
            NSMutableDictionary *mutableDic = [NSMutableDictionary dictionaryWithDictionary:dict];
            [mutableDic setValue:value forKey:@"v"];
            [mutableArr replaceObjectAtIndex:i withObject:[mutableDic copy]];
        }
    }
    
    self.array1 = [mutableArr copy];
    [self.tableView reloadData];

}

- (NSInteger)sexIndex:(NSString *)value
{
    if ([value isEqualToString:@"男"]) {
        return 1;
    } if ([value isEqualToString:@"女"]) {
        return 2;
    }
    return 1;
}

- (NSArray *)majors
{
    return @[@"住院医师",@"主治医师",@"副主任医师",@"主任医师"];
}


#pragma mark UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    self.cur_textView = textView;
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    _intro = textView.text;
}

#pragma mark 上传图片
- (IBAction)uploadButtonAction:(id)sender
{
    NSString *key = objc_getAssociatedObject(sender, @"button.key");
    self.m_key = key;
    [self pickImageAction];
}
// 上传图片 开始
- (void)requestUploadImage:(UIImage *)image
{
    [MMProgressHUD showWithTitle:@"上传图片中"];
    //1.创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    NSString *token = [LTPCacheManager shareInstance].token;
    token = [NSString stringWithFormat:@"Bearer %@",token];
    
    [manager.requestSerializer setValue:token forHTTPHeaderField:@"authorization"];
    
    NSString *uploadUrl = [NSString stringWithFormat:@"%@%@", BASE_URL, @"/common/file/upload"];
    [manager POST:uploadUrl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
        
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"file.jpg" mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印上传进度
        CGFloat progress = 100.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
        NSLog(@"%.2lf%%", progress);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MMProgressHUD updateProgress:progress withStatus:@"上传中"];
        });
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject
                                                            options:NSJSONReadingMutableContainers
                                                              error:nil];
        ImageInfo *imgModel = [ImageInfo modelWithDictionary:dic[@"data"][@"file"]];
        NSLog(@"上传成功：%@",imgModel);
        [self setImageModel:imgModel];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MMProgressHUD dismissWithSuccess:@"上传成功"];
            [self.tableView reloadData];
        });

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        dispatch_async(dispatch_get_main_queue(), ^{
            [MMProgressHUD dismissWithError:@"上传失败"];
        });
        NSLog(@"上传失败：%@",error);
    }];
}

- (void)setImageModel:(ImageInfo *)imgInfo
{
    NSMutableArray *mutableArr = [NSMutableArray arrayWithArray:self.array2];
    for (int i=0;i<self.array2.count;i++) {
        NSDictionary *dict = mutableArr[i];
        NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithDictionary:dict];
        NSString *key = mutableDict[@"key"];
        if ([key isEqualToString:self.m_key]) {
            [mutableDict setValue:imgInfo forKey:@"imageInfo"];
            [mutableArr replaceObjectAtIndex:i withObject:[mutableDict copy]];
            self.array2 = [mutableArr copy];
            break;
        }
    }
}

// 选择图片
- (void)pickImageAction
{
    UIAlertController *alerVC = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    NSArray *array = @[@"相册", @"拍照"];
    for (int i=0; i<[array count]; i++) {
        [alerVC addAction:[UIAlertAction actionWithTitle:array[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            if ([array indexOfObject:action.title] == 0) {
                [self createUIImagePickerController];
            }else if ([array indexOfObject:action.title] == 0) {
                [self enterCamera];
            }
        }]];
    }
    [alerVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {    }]];
    [self presentViewController:alerVC animated:YES completion:NULL];
}


-(void)createUIImagePickerController {
    
    UIImagePickerController *imagePickerCtr = [[UIImagePickerController alloc] init];
    [imagePickerCtr setAllowsEditing:NO];
    imagePickerCtr.delegate = self;
    [self presentViewController:imagePickerCtr animated:YES completion:nil];
}

-(void)enterCamera {
    
    UIImagePickerController *imagePickerCtr = [[UIImagePickerController alloc] init];
    imagePickerCtr.delegate = self;
    [imagePickerCtr setAllowsEditing:NO];
    imagePickerCtr.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:imagePickerCtr animated:YES completion:nil];
    
}


#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *realImage = info[UIImagePickerControllerOriginalImage];
    UIImage* image = [self imageScaleForSiYue:realImage];
    // 开始上传
    [self requestUploadImage:image];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

-(UIImage *)imageScaleForSiYue:(UIImage*)image
{
    float XIANZHIWIDTH = 640;
    float imgWidth = image.size.width;
    float imgHeight = image.size.height;
    if (imgWidth==imgHeight) {
        if (imgWidth>XIANZHIWIDTH) {
            return [AuthenticateAddTableViewController imageWithImageSimple:image scaledToSize:CGSizeMake(XIANZHIWIDTH, XIANZHIWIDTH)];
        }
    }
    if (imgWidth>imgHeight) {
        if (imgHeight>XIANZHIWIDTH) {
            float widthR = XIANZHIWIDTH/(image.size.height/image.size.width);
            return [AuthenticateAddTableViewController imageWithImageSimple:image scaledToSize:CGSizeMake(widthR, XIANZHIWIDTH)];
        }
    }else {
        if (imgWidth>XIANZHIWIDTH) {
            float heightR = XIANZHIWIDTH/(image.size.width/image.size.height);
            return [AuthenticateAddTableViewController imageWithImageSimple:image scaledToSize:CGSizeMake(XIANZHIWIDTH, heightR)];
        }
    }
    return image;
}

+ (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}

@end
